<?php

/**
 * Register user authorized by social network
 *
 * @param array $params - required key: id
 * @return boolean
 */
function authorizeBySocialNetwork($params)
{
   if(session::user()) return TRUE;

   if(!empty($params['network']))
   {  
      switch($params['network'])
      {
         case 'facebook':
            
            # GET USER'S ACCESS TOKEN
            if(empty($params['token']) && !empty($_COOKIE['fbs_'. config::read('facebook_api')]))
            {
               $token = $_COOKIE['fbs_'. config::read('facebook_api')];
               $token = substr($token, 1, -1);
               if(strpos($token, 'access_token') !== FALSE)
               {
                  parse_str($token);
                  $params['token'] = $access_token;
               }
            }

            # GET USER'S INFO TO SAVE IN DB
            if(!empty($params['token']))
            {
               $url = 'https://graph.facebook.com/me?access_token='. $params['token'];
               $respond = @file_get_contents($url);

               if(!empty($respond))
               {
                  $respond = json_decode($respond);
                  $USER = new user();
                  $USER->loadByLogin($respond->username);
                  if($USER->id && $USER->type == 'facebook')
                  {
                     $r = TRUE;
                     session::makeAuthorized($USER);
                  }

                  if(!$r)
                  {
                     $USER = new user();
                     $USER->type = 'facebook';
                     $user_data = array(
                        'login'    => $respond->username,
                        'name'     => $respond->first_name,
                        'surname'  => $respond->last_name,
                        'gender'   => ($respond->gender == 'male' ? 1 : 2),
                        'birthday' => NULL,
                        'active'   => 1
                     );
                     
                     # GRAB USER'S IMAGE
                     // TODO: генерировать строку с параметрами изображения на основании данных настроек поля
                     $url = 'https://graph.facebook.com/'. $respond->username .'/picture?access_token='. $params['token'];
                     copy($url, ROOT .'/tmp/'. $respond->username .'.jpg');
                     if(
                        file_exists(ROOT .'/tmp/'. $respond->username .'.jpg') && 
                        ($finfo = getimagesize(ROOT .'/tmp/'. $respond->username .'.jpg')))
                     {
                        $u_image  = 'path%5B0%5D='. $respond->username .'.jpg';
                        $u_image .= '&crop%5B0%5D%5Bx%5D=0&crop%5B0%5D%5By%5D=0';
                        $u_image .= '&crop%5B0%5D%5Bw%5D='. $finfo[0];
                        $u_image .= '&crop%5B0%5D%5Bh%5D='. $finfo[1];
                        $u_image .= '&crop%5B1%5D%5Bx%5D=0&crop%5B1%5D%5By%5D=0';
                        $u_image .= '&crop%5B1%5D%5Bw%5D='. $finfo[0];
                        $u_image .= '&crop%5B1%5D%5Bh%5D='. $finfo[1];
                        
                        $user_data['pics'] = $u_image;
                     }
                     
                     $r = $USER->save($user_data);
                     if($r)
                     {
                        $USER->setGroups(2);
                        $r = $USERS->authorizeBySocialNetwork($respond->username, 'facebook');
                     }
                  }
                  
                  if($r) return TRUE;
               }
            }
            
            return FALSE;
            break;
            
            
            
            
         case 'vkontakte':
            if(!empty($params['token']))
            {
               $args = array(
                  'api_id'    => config::read('vkontakte_api'),
                  'format'    => 'json',
                  'method'    => 'getProfiles',
                  'uids'      => $params['token'],
                  'v'         => '3.0',
                  'fields'    => 'uid,first_name,last_name,screen_name,sex,bdate,city,country,photo'
               );
               
               $url  = 'https://api.vkontakte.ru/api.php?sig=';
               
               $sig = array();
               foreach ($args as $key => $val) $sig[] = $key .'='. $val;
               sort($sig);
               $url .= md5(implode('', $sig). config::read('vkontakte_secret'));
               foreach ($args as $key => $val) $url .= "&$key=$val";
               
               $respond = @file_get_contents($url);
               $respond = json_decode($respond);
               
               if($respond && !empty($respond->response) && is_array($respond->response))
               {
                  $respond = reset($respond->response);
                  $USER = new user();
                  $USER->loadByLogin($respond->screen_name);
                  if($USER->id && $USER->type == 'vkontakte')
                  {
                     $r = TRUE;
                     session::makeAuthorized($USER);
                  } 
                  
                  if(!$r)
                  {
                     $USER = new user();
                     $USER->type = 'vkontakte';
                     $user_data = array(
                        'login'    => $respond->screen_name,
                        'name'     => $respond->first_name,
                        'surname'  => $respond->last_name,
                        'gender'   => ($respond->sex == 2 ? 1 : 2),
                        'city'     => !empty($respond->city) ? $respond->city : '',
                        'country'  => !empty($respond->country) ? $respond->country : '',
                        'birthday' => NULL,
                        'active'   => 1
                     );
                     if(!empty($respond->photo))
                     {
                        copy($respond->photo, ROOT .'/tmp/'. $respond->screen_name .'.jpg');
                        if(
                           file_exists(ROOT .'/tmp/'. $respond->screen_name .'.jpg') && 
                           ($finfo = getimagesize(ROOT .'/tmp/'. $respond->screen_name .'.jpg')))
                        {
                           $u_image  = 'path%5B0%5D='. $respond->screen_name .'.jpg';
                           $u_image .= '&crop%5B0%5D%5Bx%5D=0&crop%5B0%5D%5By%5D=0';
                           $u_image .= '&crop%5B0%5D%5Bw%5D='. $finfo[0];
                           $u_image .= '&crop%5B0%5D%5Bh%5D='. $finfo[1];
                           $u_image .= '&crop%5B1%5D%5Bx%5D=0&crop%5B1%5D%5By%5D=0';
                           $u_image .= '&crop%5B1%5D%5Bw%5D='. $finfo[0];
                           $u_image .= '&crop%5B1%5D%5Bh%5D='. $finfo[1];
                           
                           $user_data['pics'] = $u_image;
                        }
                     }
                     
                     $r = $USER->save($user_data);
                     if($r)
                     {
                        $USER->setGroups(2);
                        $r = $USERS->authorizeBySocialNetwork($respond->screen_name, 'vkontakte');
                     }
                  }
               }
               
               if($r) return TRUE;
            }
            break;
      }
   }
   
   return FALSE;
}


function logout()
{
   session::logout();
   return TRUE;
}